import datetime

from django import template

register = template.Library()


@register.filter
def next_month(now_date):
    # now_date = datetime.datetime.strptime(str_now_date, '%Y-%m-%d')
    nmonth = now_date.month + 1
    year = now_date.year
    if nmonth > 12:
        nmonth -= 12
        year += 1

    next_date = datetime.date(year=year, month=nmonth, day=1)
    return next_date


@register.filter
def last_month(now_date):
    # now_date = datetime.datetime.strptime(str_now_date, '%Y-%m-%d')
    lmonth = now_date.month - 1
    year = now_date.year
    if lmonth == 12:
        lmonth = 12
        year -= 1

    last_date = datetime.date(year=year, month=lmonth, day=1)
    return last_date


@register.simple_tag(takes_context=True)
def active_view(context, name=None, url=None, re=None, cond=True):
    '''
    获得当前页面的url_name并根据指定name,url,re等信息指定是否在页面样式里增加active样式

    custom tag "active_view" to return 'active' in the template when the view is active
    usage : {% active_view name='view-name' %}
    usage : {% active_view uest url='/view/abs/url' %}
    usage : {% active_view re='^/view/ur.*' %}

    :param context:
    :param name:
    :param url:
    :param re:
    :param cond:
    :return:
    '''
    request = context.request
    if name is not None:
        return 'active' if request.resolver_match.url_name == name and cond else ''
    elif url is not None:
        return 'active' if request.path_info == url and cond else ''
    elif re is not None:
        import re as _
        return 'active' if _.search(re, request.path_info) and cond else ''
    return ''
